package com.smartpro.mis.modular.business.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.utils.qrcode.QrcodeUtils;
import com.smartpro.mis.core.base.controller.BaseController;
import com.smartpro.mis.core.base.tips.ErrorTip;
//import com.smartpro.mis.core.common.annotion.BussinessLog;
//import com.smartpro.mis.core.common.constant.dictmap.UserDict;
import com.smartpro.mis.core.base.tips.SuccessTip;
import com.smartpro.mis.modular.business.neo4jEntity.*;
import com.smartpro.mis.modular.business.service.*;
import com.smartpro.mis.modular.system.dao.*;
import com.smartpro.mis.modular.system.model.*;
import com.smartpro.mis.rest.modular.auth.controller.dto.ResponseBean;
import com.smartpro.mis.rest.modular.auth.util.JwtTokenUtil;
import com.smartpro.mis.rest.modular.auth.util.NewImageUtils;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
//import com.smartpro.mis.core.log.LogObjectHolder;

import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 商品控制器
 *
 * @author mengiy
 * @Date 2019-04-10 16:55:48
 */
@RestController
@RequestMapping("/api/service/product")
public class ProductController extends BaseController {


    @Autowired
    private IProductService productService;
    @Autowired
    private IProductClassService productClassService;
    @Autowired
    private IPriceService priceService;
    @Autowired
    private IUserService userService;

    @Autowired
    private IDistributorService distributorService;
    @Autowired
    private IPositionService positionService;

    @Autowired
    private IPerformanceService performanceService;


    @Autowired
    private ClickDistributorRelationRepository clickDistributorRelationRepository;
    @Autowired
    private ClickLinkRelationRepository clickLinkRelationRepository;

    @Autowired
    private N4jProductRepository n4jProductRepository;

    @Autowired
    private N4jDistributorRepository n4jDistributorRepository;
    @Autowired
    private DistributorExpireRelationRepository distributorExpireRelationRepository;
    @Autowired
    private DistributorProtectRelationRepository distributorProtectRelationRepository;


    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 获取商品列表 @RequestBody Map params
     */
    @ApiOperation(value = "查询商品列表",notes="获取全部商品列表" )
//    @BussinessLog(value = "API查询所有商品", key = "id", dict = UserDict.class)
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @RequiresAuthentication
    public Object list() {
        JSONObject result = new JSONObject();
        try {
            List<Product> list = this.productService.selectList(null);
            List<JSONObject> proList = new ArrayList<>();
            //补充价格详情
            for(Product p : list) {
                JSONObject json = (JSONObject) JSONObject.toJSON(p);
               int productId = p.getProductID();
                Map<String,Object> condition  = new HashMap<>();
                condition.put("productID",productId);
                List<Price> priceList = this.priceService.selectByMap(condition);
                json.put("priceList",JSONArray.parseArray(JSON.toJSONString(priceList)));
                proList.add(json);
            }
            result.put("code",200);
            result.put("message","操作成功");
            result.put("data",proList);
        }catch (Exception e){
            result.put("code",400);
            result.put("message",e.getMessage());
            result.put("data",null);
        }
        return result;
    }


    /**
     * 分页查询商品列表
     */
    @ApiOperation(value = "分页查询商品列表",notes="分页获取商品列表" )
    @ApiImplicitParam(name ="pageJSON",value = "包含字段：起始页: start,每页的条数: num", required = true, dataType = "JSONObject")
    @RequestMapping(value = "/selectByPage",method = RequestMethod.POST)
    @RequiresAuthentication
    public Object selectByPage(@RequestBody JSONObject pageJSON) {
        JSONObject result = new JSONObject();
        int start = pageJSON.getInteger("start");
        int num = pageJSON.getInteger("num");
        try {
            List<Product> list = this.productService.selectListByPage(start,num);
            List<JSONObject> proList = new ArrayList<>();
            //补充价格详情
            for(Product p : list) {
                JSONObject json = (JSONObject) JSONObject.toJSON(p);
                int productId = p.getProductID();
                Map<String,Object> condition  = new HashMap<>();
                condition.put("productID",productId);
                List<Price> priceList = this.priceService.selectByMap(condition);
                json.put("priceList",JSONArray.parseArray(JSON.toJSONString(priceList)));
                proList.add(json);
            }
            result.put("code",200);
            result.put("message","操作成功");
            result.put("data",proList);
        }catch (Exception e){
            result.put("code",400);
            result.put("message",e.getMessage());
            result.put("data",null);
        }
        return result;
    }

    /**
     * 查看可推广商品列表
     */
    @ApiOperation(value = "查看可推广商品列表",notes="推广员登录状态下查看可推广商品列表" )
    @RequestMapping(value = "/getProductList",method = RequestMethod.GET)
    @RequiresAuthentication
    public Object getProductList(HttpServletRequest request) {

        JSONObject result = new JSONObject();
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader("Authorization");
        JwtTokenUtil jwt = new JwtTokenUtil();
        String username = jwt.getUsernameFromToken(authorization);
        Map<String,Object> condtion = new HashMap();
        condtion.put("wechat",username);
        User user = this.userService.selectByMap(condtion).get(0);
        int userID = user.getUserID();
        Distributor distributor = this.distributorService.selectById(userID);

        Map<String,Object> performanceCondition = new HashMap<>();
        performanceCondition.put("distributorID",userID);
        List<Performance> pList = this.performanceService.selectByMap(performanceCondition);

        List<JSONObject> productList = new ArrayList<>();
        Map<String,Object> productCondition = new HashMap<>();
        productCondition.put("isDistribution",0);
        productCondition.put("isDeleted",1);

        List<Product> products = this.productService.selectByMap(productCondition);
        for(Product product: products){
            JSONObject json = new JSONObject();
            json.put("productID",product.getProductID());
            json.put("smallPicture",product.getSmallPicture());
            json.put("name",product.getName());
            json.put("description",product.getDescription());
            json.put("productURL",product.getProductURL());
            json.put("tagList",product.getTags());
            //获取价格
            Map<String,Object> pmap = new HashMap<>();
            pmap.put("productID",product.getProductID());
            List<Price> prices = this.priceService.selectByMap(pmap);
            List<JSONObject> priceList = new ArrayList<>();
            for(Price price:prices){
                JSONObject pjson = new JSONObject();
                pjson.put("specList",price.getSpecList());
                pjson.put("instantPrice",price.getInstantPrice());
                pjson.put("groupPrice",price.getGroupPrice());
                JSONArray personalList =  JSONArray.parseArray(price.getPersonalList());
                BigDecimal income = null;
                //标号标记要跳出的循环
                outterLoop: for(int i=0;i<personalList.size();i++){
                    JSONObject o = personalList.getJSONObject(i);
                    for(String s:o.keySet()){
                        if(s.contains(userID+"")){
                            income = o.getBigDecimal(s);
                            break outterLoop; // 会跳出标号标记的那个循环
                        }
                    }
                }
                pjson.put("income",income);
                priceList.add(pjson);

            }
            json.put("price",priceList);
            productList.add(json);

        }

        result.put("belongToCompany",distributor.getBelongToCompany());
        result.put("amountOfOrders",pList.size());
        result.put("productList",productList);

        return  new ResponseBean(200,"query success",result);
    }



    /**
     * 动态查看推广员可推广商品列表
     */
    @ApiOperation(value = "推广员自定义查看可推广商品列表",notes="需要传递参数是否置于首页OnHomepage，是否进行推广isDistribution" )
    @ApiImplicitParam(name = "paramJSON",value = "推广产品过滤参数,包括是否置于首页：onHomepage，是否进行推广：isDistribution",dataType = "JSONObject",required = true)
    @RequestMapping(value = "/getMyDistProductList",method = RequestMethod.POST)
    @RequiresAuthentication
    public Object getMyDistProductList(HttpServletRequest request,@RequestBody JSONObject paramJSON) {
        JSONObject result = new JSONObject();
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader("Authorization");
        JwtTokenUtil jwt = new JwtTokenUtil();
        String username = jwt.getUsernameFromToken(authorization);
        Map<String,Object> condtion = new HashMap();
        condtion.put("wechat",username);
        User user = this.userService.selectByMap(condtion).get(0);
        int userID = user.getUserID();
        Distributor distributor = this.distributorService.selectById(userID);

        Map<String,Object> performanceCondition = new HashMap<>();
        performanceCondition.put("distributorID",userID);
        List<Performance> pList = this.performanceService.selectByMap(performanceCondition);

        int isDistribution = paramJSON.getInteger("isDistribution");
        int onHomepage = paramJSON.getInteger("onHomepage");
        List<JSONObject> productList = new ArrayList<>();
        Map<String,Object> productCondition = new HashMap<>();
        productCondition.put("isDistribution",isDistribution);
        productCondition.put("onHomepage",onHomepage);
        productCondition.put("isDeleted",1);

        List<Product> products = this.productService.selectByMap(productCondition);
        for(Product product: products){
            JSONObject json = new JSONObject();
            json.put("productID",product.getProductID());
            json.put("smallPicture",product.getSmallPicture());
            json.put("name",product.getName());
            json.put("description",product.getDescription());
            json.put("productURL",product.getProductURL());
            json.put("tagList",product.getTags());
            //获取价格
            Map<String,Object> pmap = new HashMap<>();
            pmap.put("productID",product.getProductID());
            List<Price> prices = this.priceService.selectByMap(pmap);
            List<JSONObject> priceList = new ArrayList<>();
            for(Price price:prices){
                JSONObject pjson = new JSONObject();
                pjson.put("specList",price.getSpecList());
                pjson.put("instantPrice",price.getInstantPrice());
                pjson.put("groupPrice",price.getGroupPrice());
                JSONArray personalList =  JSONArray.parseArray(price.getPersonalList());
                BigDecimal income = null;
                //标号标记要跳出的循环
                outterLoop: for(int i=0;i<personalList.size();i++){
                    JSONObject o = personalList.getJSONObject(i);
                    for(String s:o.keySet()){
                        if(s.contains(userID+"")){
                            income = o.getBigDecimal(s);
                            break outterLoop; // 会跳出标号标记的那个循环
                        }
                    }
                }
                pjson.put("income",income);
                priceList.add(pjson);

            }
            json.put("price",priceList);
            productList.add(json);

        }

        result.put("belongToCompany",distributor.getBelongToCompany());
        result.put("amountOfOrders",pList.size());
        result.put("productList",productList);

        return  new ResponseBean(200,"query success", result);
    }


    /**
     * 查看商品列表首页
     */
    @ApiOperation(value = "查看商品列表首页",notes="查看商品列表首页" )
    @RequestMapping(value = "/getHomeProductList",method = RequestMethod.GET)
    @RequiresAuthentication
    @ResponseBody
    public Object getHomeProductList() {
        JSONObject result = new JSONObject();
        List<JSONObject> bannerList = new ArrayList<>();
        Map bannerQuery = new HashMap();
        bannerQuery.put("onBanner",0);
        List<Product> products = productService.selectByMap(bannerQuery);
        for(Product p :products){
            JSONObject json = new JSONObject();
            json.put("productID",p.getProductID());
            json.put("bigPicture",p.getBigPicture());
            json.put("productURL",p.getProductURL());
            json.put("sequence",p.getSequence());
            bannerList.add(json);

        }
        result.put("bannerList",bannerList);



        //获取商品首页列表
        List<Map<String,Object>> resList = productService.getHomeProductList(null,null,0,0,0);
        List<JSONObject> classList = new ArrayList<>();
        List<JSONObject> classList1 = new ArrayList<>();
        String currClassName = null;

        for(int i=0;i<resList.size();i++){
            Map<String,Object> map = resList.get(i);

            if(i==0){
                currClassName = (String)map.get("className");
            }
            String className =(String)map.get("className");

            //组装数据
            JSONObject classObj = new JSONObject();
            classObj.put("productID",(Integer)map.get("productID"));
            classObj.put("name",(String)map.get("name"));
            classObj.put("smallPicture",(String)map.get("smallPicture"));
            classObj.put("description",(String)map.get("description"));
            classObj.put("tags",(String)map.get("tags"));

            int numberOfMember = 0;
            if(null != map.get("numberOfMember"))
                numberOfMember = (Integer) map.get("numberOfMember");
            classObj.put("numberOfMember",numberOfMember);

            int currentNumber = 0;
            if(null!= map.get("memberList")){
                String memberList = (String)map.get("memberList");
                if (memberList.contains(","))
                    currentNumber = memberList.split(",").length;
                else
                    currentNumber =1;

            }
            classObj.put("currentNumber",currentNumber);

            String specList = null;
            if(null != map.get("specList"))
                specList = (String) map.get("specList");
            classObj.put("specList",specList);

            BigDecimal instantPrice = null;
            if(null != map.get("instantPrice"))
                instantPrice = (BigDecimal) map.get("instantPrice");
            classObj.put("instantPrice",instantPrice);
            BigDecimal groupPrice = null;
            if(null != map.get("groupPrice"))
                groupPrice = (BigDecimal) map.get("groupPrice");
            classObj.put("groupPrice",groupPrice);
            BigDecimal leaderPrice = null;
            if(null != map.get("leaderPrice"))
                leaderPrice = (BigDecimal) map.get("leaderPrice");
            classObj.put("leaderPrice",leaderPrice);
            int duration = 0;
            if(null != map.get("duration"))
                duration = (Integer) map.get("duration");
            classObj.put("duration",duration);
            int isMultiple = 0;
            if(null != map.get("isMultiple"))
                isMultiple = (Integer) map.get("isMultiple");
            classObj.put("isMultiple",isMultiple);
            int sequence = 0;
            if(null != map.get("sequence"))
                sequence = (Integer) map.get("sequence");
            classObj.put("sequence",sequence);


            if(className.equals(currClassName)){

                classList1.add(classObj);

            }else {
                JSONObject obj = new JSONObject();
                obj.put(currClassName,classList1);
                classList.add(obj);
                currClassName = className;
                classList1 = new ArrayList<>();
                classList1.add(classObj);

            }
            if(i==resList.size()-1){
                JSONObject obj = new JSONObject();
                obj.put(currClassName,classList1);
                classList.add(obj);
            }
        }

        result.put("homepageClassList",classList);
        return new ResponseBean(200,"operation success",result);
    }



    /**
     * 查看全部分组商品
     */
    @ApiOperation(value = "查看全部分组商品",notes="查看全部分组商品" )
    @ApiImplicitParam(name = "params",value = "json包含元素：start,num",required = true)
    @RequestMapping(value = "/getAllClassProduct",method = RequestMethod.POST)
    @ResponseBody
    @RequiresAuthentication
    public Object getAllClassProduct(@RequestBody JSONObject params) {
        int start = params.getInteger("start");
        int num = params.getInteger("num");
        List<Map<String,Object>> resList = productService.getProductList(null,null,start,num);
        List<JSONObject> classList = new ArrayList<>();
        List<JSONObject> classList1 = new ArrayList<>();
        String currClassName = null;

        for(int i=0;i<resList.size();i++){
            Map<String,Object> map = resList.get(i);

            if(i==0){
                currClassName = (String)map.get("className");
            }
            String className =(String)map.get("className");

            //组装数据
            JSONObject classObj = new JSONObject();
            classObj.put("productID",(Integer)map.get("productID"));
            classObj.put("name",(String)map.get("name"));
            classObj.put("smallPicture",(String)map.get("smallPicture"));
            classObj.put("description",(String)map.get("description"));
            classObj.put("tags",(String)map.get("tags"));

            int numberOfMember = 0;
            if(null != map.get("numberOfMember"))
                numberOfMember = (Integer) map.get("numberOfMember");
            classObj.put("numberOfMember",numberOfMember);

            int currentNumber = 0;
            if(null!= map.get("memberList")){
                String memberList = (String)map.get("memberList");
                if (memberList.contains(","))
                    currentNumber = memberList.split(",").length;
                else
                    currentNumber =1;

            }
            classObj.put("currentNumber",currentNumber);

            String specList = null;
            if(null != map.get("specList"))
                specList = (String) map.get("specList");
            classObj.put("specList",specList);

            BigDecimal instantPrice = null;
            if(null != map.get("instantPrice"))
                instantPrice = (BigDecimal) map.get("instantPrice");
            classObj.put("instantPrice",instantPrice);
            BigDecimal groupPrice = null;
            if(null != map.get("groupPrice"))
                groupPrice = (BigDecimal) map.get("groupPrice");
            classObj.put("groupPrice",groupPrice);
            BigDecimal leaderPrice = null;
            if(null != map.get("leaderPrice"))
                leaderPrice = (BigDecimal) map.get("leaderPrice");
            classObj.put("leaderPrice",leaderPrice);
            int duration = 0;
            if(null != map.get("duration"))
                duration = (Integer) map.get("duration");
            classObj.put("duration",duration);
            int isMultiple = 0;
            if(null != map.get("isMultiple"))
                isMultiple = (Integer) map.get("isMultiple");
            classObj.put("isMultiple",isMultiple);
            int sequence = 0;
            if(null != map.get("sequence"))
                sequence = (Integer) map.get("sequence");
            classObj.put("sequence",sequence);


            if(className.equals(currClassName)){

                classList1.add(classObj);

            }else {
                JSONObject obj = new JSONObject();
                obj.put(currClassName,classList1);
                classList.add(obj);
                currClassName = className;
                classList1 = new ArrayList<>();
                classList1.add(classObj);

            }
            if(i==resList.size()-1){
                JSONObject obj = new JSONObject();
                obj.put(currClassName,classList1);
                classList.add(obj);
            }
        }

        return new ResponseBean(200,"operation success",classList);
    }


    /**
     * 多条件查询商品
     */
    @ApiOperation(value = "多条件查询商品",notes="多条件筛选商品" )
    @ApiImplicitParam(name = "params", value = "json格式查询条件", required = true, dataType = "Map")
//    @BussinessLog(value = "API多条件查询设备", key = "id", dict = UserDict.class)
    @RequestMapping(value = "/mulQuery",method = RequestMethod.POST)
    @RequiresAuthentication
    public Object mulQuery(@RequestBody Map params) {
        JSONObject result = new JSONObject();
        Map<String, Object> queryParams = new HashMap<String, Object>();
        try {
            if(params.containsKey("className")){
                Map condtion = new HashMap();
                condtion.put("className",params.get("className"));
                List<ProductClass> productClassList = this.productClassService.selectByMap(condtion);
                if(null != productClassList && productClassList.size()>0){
                    ProductClass productClass = productClassList.get(0);
                    queryParams.put("classID",productClass.getClassID());
                }
            }
            List<Product> list = productService.selectByMap(queryParams);
            List<JSONObject> proList = new ArrayList<>();
            //补充价格详情
            for(Product p : list) {
                JSONObject json = (JSONObject) JSONObject.toJSON(p);
               int productId = p.getProductID();
                Map<String,Object> condition  = new HashMap<>();
                condition.put("productID",productId);
                List<Price> priceList = this.priceService.selectByMap(condition);
                json.put("priceList",JSONArray.parseArray(JSON.toJSONString(priceList)));
                proList.add(json);
            }
            result.put("code",200);
            result.put("message","操作成功");
            result.put("data", proList);
        }catch (Exception e){
            result.put("code",400);
            result.put("message",e.getMessage());
            result.put("data",null);
        }
        return result;
    }


    /**
     * 微信端查看商品列表首页
     */
/*

    @ApiOperation(value = "微信端查看商品列表首页",notes="获取banner列表和商品分组列表" )
//    @BussinessLog(value = "API多条件查询设备", key = "id", dict = UserDict.class)
    @RequestMapping(value = "/getHomeProductList",method = RequestMethod.GET)
    public Object getHomeProductList() {
        JSONObject result = new JSONObject();


        return new ResponseBean(200,"query success",result);
    }

*/

    /**
     * 新增商品
     */
    @ApiOperation(value ="新增商品")
    @ApiImplicitParam(name = "product", value = "商品详细信息", required = true, dataType = "Product")
//    @BussinessLog(value = "新增商品", key = "id", dict = UserDict.class)
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @RequiresAuthentication
    @ResponseBody
    public Object add(@RequestBody JSONObject priceInfo ) {
        JSONObject result = new JSONObject();
        System.out.println(priceInfo.toJSONString());
        int productID = 0;
        Product product = new Product();
        Price price = new Price();
        try {
          String name = priceInfo.getString("name");
          String description = priceInfo.getString("description");
          String smallPicture = priceInfo.getString("smallPicture");
          String bigPicture = priceInfo.getString("bigPicture");
          String productURL = priceInfo.getString("productURL");
          String poster = priceInfo.getString("poster");
          int onHomepage = priceInfo.getInteger("onHomepage");
          int onBanner = priceInfo.getInteger("onBanner");
          String className = priceInfo.getString("className");
          int saleType = priceInfo.getInteger("saleType");
          String madeBy = priceInfo.getString("madeBy");
          String offlineTime = priceInfo.getString("offlineTime");
          JSONArray tags = priceInfo.getJSONArray("tags");

          int isGroupBuy = priceInfo.getInteger("isGroupBuy");
          int isPost = priceInfo.getInteger("isPost");
          String resultURL = priceInfo.getString("resultURL");

          int canRefund = priceInfo.getInteger("canRefund");

          String latestRefundTime = priceInfo.getString("latestRefundTime");
//          int refundDays = priceInfo.getInteger("refundDays");
          if(null !=priceInfo.get("refundDays")){
                int refundDays = priceInfo.getInteger("refundDays");
                product.setIssueDays(refundDays);
          }
          int issueImme = priceInfo.getInteger("issueImme");
          String issueTime = priceInfo.getString("issueTime");

//          int issueDays = priceInfo.getInteger("issueDays");
         if(null !=priceInfo.get("issueDays")){
                int issueDays = priceInfo.getInteger("issueDays");
                product.setIssueDays(issueDays);
            }
          int isIssueOffline = priceInfo.getInteger("isIssueOffline");
          int numberOfMember = (Integer) priceInfo.get("numberOfMember");
          int duration = (Integer) priceInfo.get("duration");
          int status = (Integer) priceInfo.get("status");
          if(null != priceInfo.get("isDistribution")){
              int isDistribution = (Integer) priceInfo.get("isDistribution");
              product.setIsDistribution(isDistribution);
          }

          product.setName(name);
          product.setDescription(description);
          product.setSmallPicture(smallPicture);
          product.setBigPicture(bigPicture);
          product.setProductURL(productURL);
          product.setPoster(poster);
          product.setOnHomepage(onHomepage);
          product.setOnBanner(onBanner);
          //设置商品分组编号
          HashMap proClassMap = new HashMap();
          proClassMap.put("className", className);
          ProductClass productClass = (ProductClass) this.productClassService.selectByMap(proClassMap).get(0);
          product.setClassID(productClass.getClassID());

          product.setSaleType(saleType);
          product.setMadeBy(madeBy);
          product.setOfflineTime(offlineTime);
          product.setTags(tags.toJSONString());
          product.setStatus(status);
          product.setNumberOfMember(numberOfMember);
          product.setDuration(duration);
          product.setIsGroupBuy(isGroupBuy);
          product.setIsPost(isPost);
          product.setResultURL(resultURL);
          product.setCanRefund(canRefund);
          product.setLatestRefundTime(latestRefundTime);
//          product.setRefundDays(refundDays);
          product.setIssueImme(issueImme);
          product.setIssueTime(issueTime);

          product.setIsIssueOffline(isIssueOffline);
          product.setCreateTime(sdf.format(new Date()));
          this.productService.insertID(product);
          productID = product.getProductID();


//设置价格策略
          JSONArray priceLists = priceInfo.getJSONArray("priceList");
          for(int i = 0;i<priceLists.size();i++){
              JSONObject priceList = priceLists.getJSONObject(i);
              JSONArray specList =  priceList.getJSONArray("specList");
              BigDecimal originalPrice = priceList.getBigDecimal("originalPrice");
              BigDecimal instantPrice = priceList.getBigDecimal("instantPrice");
              BigDecimal groupPrice = priceList.getBigDecimal("groupPrice");
//              BigDecimal instantPrice = new BigDecimal((String)priceList.get("instantPrice")).setScale(2,BigDecimal.ROUND_HALF_UP);
//              BigDecimal groupPrice = new BigDecimal((String)priceList.get("groupPrice")).setScale(2,BigDecimal.ROUND_HALF_UP);
//              BigDecimal leaderPrice =  new BigDecimal((String)priceList.get("leaderPrice")).setScale(2,BigDecimal.ROUND_HALF_UP);
              BigDecimal leaderPrice = priceList.getBigDecimal("leaderPrice");
              JSONArray personalList =  priceList.getJSONArray("personalList");
              JSONArray incomeClassList = priceList.getJSONArray("incomeClassList");

              int isMultiple = (Integer) priceList.get("isMultiple");

              price.setSpecList(specList.toJSONString());
              price.setOriginalPrice(originalPrice);
              price.setInstantPrice(instantPrice);
              price.setGroupPrice(groupPrice);
              price.setLeaderPrice(leaderPrice);
              price.setPersonalList(personalList.toJSONString());
              price.setIncomeClassList(incomeClassList.toJSONString());
              price.setIsMultiple(isMultiple);
              price.setProductID(productID);
              price.setCreateTime(sdf.format(new Date()));
              this.priceService.insert(price);
          }
      }catch (Exception e){
          System.err.println("新增商品失败");
          this.productService.deleteById(productID);
          Map condition = new HashMap();
          condition.put("productID",productID);
          this.priceService.deleteByMap(condition);
          result.put("code",400);
          result.put("message",e.getMessage());
          result.put("data",priceInfo);
          return result;
      }

        this.n4jProductRepository.save(new N4jProduct(productID));
        result.put("code",200);
        result.put("message", "操作成功");
        result.put("data",JSONObject.toJSONString(product));
        return result;
    }

    /**
     * 删除商品
     */
    @ApiOperation(value ="删除商品")
    @ApiImplicitParam(name = "productId", value = "商品编号", required = true, dataType = "Integer")
    @RequestMapping(value = "/delete",method = RequestMethod.GET)
    @ResponseBody
    @RequiresAuthentication
    public Object delete(@RequestParam Integer productId) {
        productService.deleteById(productId);
        return new ResponseBean(200,"delete success",null);
    }

    /**
     * 修改商品
     */
    @ApiOperation(value ="修改商品")
    @ApiImplicitParam(name = "product", value = "商品详细信息", required = true, dataType = "Product")
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ResponseBody
    @RequiresAuthentication
    public Object update(@RequestBody JSONObject priceInfo) {
        JSONObject result = new JSONObject();

        Product product = new Product();
        int productID = priceInfo.getInteger("productID");
        String name = priceInfo.getString("name");
        String description = priceInfo.getString("description");
        String smallPicture = priceInfo.getString("smallPicture");
        String bigPicture = priceInfo.getString("bigPicture");
        String productURL = priceInfo.getString("productURL");
        String poster = priceInfo.getString("poster");
        int onHomepage = priceInfo.getInteger("onHomepage");
        int onBanner = priceInfo.getInteger("onBanner");
        //String className = priceInfo.getString("className");
        int classID = priceInfo.getInteger("classID");
        int saleType = priceInfo.getInteger("saleType");
        String madeBy = priceInfo.getString("madeBy");
        String offlineTime = priceInfo.getString("offlineTime");
        JSONArray tags = priceInfo.getJSONArray("tags");

        int isGroupBuy = priceInfo.getInteger("isGroupBuy");
        int isPost = priceInfo.getInteger("isPost");
        String resultURL = priceInfo.getString("resultURL");
        int canRefund = priceInfo.getInteger("canRefund");
        String latestRefundTime = priceInfo.getString("latestRefundTime");
        //          int refundDays = priceInfo.getInteger("refundDays");
        if(null !=priceInfo.get("refundDays")){
            int refundDays = priceInfo.getInteger("refundDays");
            product.setRefundDays(refundDays);
        }
        if(null !=priceInfo.get("isDistribution")){
            int isDistribution = priceInfo.getInteger("isDistribution");
            product.setIsDistribution(isDistribution);
        }
        int issueImme = priceInfo.getInteger("issueImme");
        String issueTime = priceInfo.getString("issueTime");

//          int issueDays = priceInfo.getInteger("issueDays");
        if(null !=priceInfo.get("issueDays")){
            int issueDays = priceInfo.getInteger("issueDays");
            product.setIssueDays(issueDays);
        }

        int isIssueOffline = priceInfo.getInteger("isIssueOffline");
        int numberOfMember = (Integer) priceInfo.get("numberOfMember");
        int duration = (Integer) priceInfo.get("duration");
        int status = (Integer) priceInfo.get("status");
        product.setName(name);
        product.setDescription(description);
        product.setSmallPicture(smallPicture);
        product.setBigPicture(bigPicture);
        product.setProductURL(productURL);
        product.setPoster(poster);
        product.setOnHomepage(onHomepage);
        product.setOnBanner(onBanner);
        //设置商品分组编号
        //HashMap proClassMap = new HashMap();
        //proClassMap.put("className", className);
       // ProductClass productClass = (ProductClass) this.productClassService.selectByMap(proClassMap).get(0);
        //product.setClassID(productClass.getClassID());
        product.setClassID(classID);
        product.setSaleType(saleType);
        product.setMadeBy(madeBy);
        product.setOfflineTime(offlineTime);
        product.setTags(tags.toJSONString());
        product.setStatus(status);
        product.setNumberOfMember(numberOfMember);
        product.setDuration(duration);
        product.setIsGroupBuy(isGroupBuy);
        product.setIsPost(isPost);
        product.setResultURL(resultURL);
        product.setCanRefund(canRefund);
        product.setLatestRefundTime(latestRefundTime);
//        product.setRefundDays(refundDays);
        product.setIssueImme(issueImme);
        product.setIssueTime(issueTime);
//        product.setIssueDays(issueDays);
        product.setIsIssueOffline(isIssueOffline);
        product.setModifyTime(sdf.format(new Date()));
        product.setProductID(productID);
        this.productService.updateById(product);


//设置价格策略
            JSONArray priceLists = priceInfo.getJSONArray("priceList");
            for(int i = 0;i<priceLists.size();i++){
                 Price price = new Price();
                JSONObject priceList = priceLists.getJSONObject(i);
                int priceID =  priceList.getInteger("priceID");
                JSONArray specList =  priceList.getJSONArray("specList");
                BigDecimal originalPrice = priceList.getBigDecimal("originalPrice");
                BigDecimal instantPrice = priceList.getBigDecimal("instantPrice");
                BigDecimal groupPrice = priceList.getBigDecimal("groupPrice");
//              BigDecimal instantPrice = new BigDecimal((String)priceList.get("instantPrice")).setScale(2,BigDecimal.ROUND_HALF_UP);
//              BigDecimal groupPrice = new BigDecimal((String)priceList.get("groupPrice")).setScale(2,BigDecimal.ROUND_HALF_UP);
//              BigDecimal leaderPrice =  new BigDecimal((String)priceList.get("leaderPrice")).setScale(2,BigDecimal.ROUND_HALF_UP);
                BigDecimal leaderPrice = priceList.getBigDecimal("leaderPrice");
                JSONArray personalList =  priceList.getJSONArray("personalList");
                JSONArray incomeClassList = priceList.getJSONArray("incomeClassList");

                int isMultiple = (Integer) priceList.get("isMultiple");
                price.setPriceID(priceID);
                price.setSpecList(specList.toJSONString());
                price.setOriginalPrice(originalPrice);
                price.setInstantPrice(instantPrice);
                price.setGroupPrice(groupPrice);
                price.setLeaderPrice(leaderPrice);
                price.setPersonalList(personalList.toJSONString());
                price.setIncomeClassList(incomeClassList.toJSONString());
                price.setIsMultiple(isMultiple);
                price.setProductID(productID);
                price.setCreateTime(sdf.format(new Date()));
                this.priceService.updateById(price);
            }

        result.put("code",200);
        result.put("message", "操作成功");
        return result;
    }

    /**
     * 商品详情
     */
    @RequestMapping(value = "/detail/{productId}")
    @ResponseBody
    @RequiresAuthentication
    public Object detail(@PathVariable("productId") Integer productId) {
        return productService.selectById(productId);
    }


    /**
     * 设置商品上下架
     */
    @ApiOperation(value ="设置商品上下架",notes = "需要参数：商品编号、商品状态,0:上架/1:下架")
    @ApiImplicitParam(name = "statusInfo", value = "包含元素：productID,status", required = true, dataType = "JSONObject")
    @RequestMapping(value = "/setProductStatus",method = RequestMethod.POST)
    @ResponseBody
    @RequiresAuthentication
    public Object setProductStatus(@RequestBody JSONObject jsonObject) {
        if(!jsonObject.containsKey("productID")||!jsonObject.containsKey("status")){
            return  new ResponseBean(400,"parameters error.",jsonObject.toJSONString());
        }
        int status = jsonObject.getInteger("status");
        int productId = jsonObject.getInteger("productID");
        Product product = productService.selectById(productId);
        product.setModifyTime(sdf.format(new Date()));
        product.setStatus(status);
        productService.updateById(product);
        return new ResponseBean(200,"operation success",product);
    }

    /**
     *用户点击推广商品链接,一方面建立图数据库的实体关联，另一方面返回商品信息
     */
    @ApiOperation(value ="用户点击取推广商品链接",notes = "需要参数：商品编号、推广员编号")
    @ApiImplicitParam(name = "disInfo", value = "包含元素：productID,distributorID", required = true, dataType = "JSONObject")
    @RequestMapping(value = "/getDistributedProduct" ,method = RequestMethod.POST)
    @ResponseBody
    @RequiresAuthentication
    public Object getDistributedProduct(HttpServletRequest request, @RequestBody JSONObject disInfo) {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader("Authorization");
        JwtTokenUtil jwt = new JwtTokenUtil();
        String username = jwt.getUsernameFromToken(authorization);
        Map<String,Object> condtion = new HashMap();
        condtion.put("wechat",username);
        User user = this.userService.selectByMap(condtion).get(0);
        int userID = user.getUserID();

        int productID = disInfo.getInteger("productID");
        N4jUser n4jUser = new N4jUser(userID);
        //定义虚拟推广员
        int distributorID  = -1;
        //判断系统是否存在虚拟推广员,不存在就新增
        N4jDistributor virtualN4jDistributor = new N4jDistributor(distributorID);
        if (null ==this.n4jDistributorRepository.findByDistributorID(distributorID)){
            n4jDistributorRepository.save(virtualN4jDistributor);
        }

        //查询过期绑定关系
        DistributorExpireRelationship de = distributorExpireRelationRepository.findExpireRelationByN4jUser(n4jUser);

        //查询有效期绑定关系
        DistributorProtectRelationship dp = distributorProtectRelationRepository.findProtectRelationByN4jUser(n4jUser);

        //当前用户没有绑定推广员，并且链接不含有推广员ID，则直接绑定虚拟推广员

        if (null == de && !disInfo.containsKey("distributorID")){

            DistributorProtectRelationship distributorProtectRelationship = new DistributorProtectRelationship(sdf.format(new Date()),0,virtualN4jDistributor,n4jUser);
            DistributorExpireRelationship distributorExpireRelationship = new DistributorExpireRelationship(sdf.format(new Date()),0,virtualN4jDistributor,n4jUser);
            distributorExpireRelationRepository.save(distributorExpireRelationship);
            distributorProtectRelationRepository.save(distributorProtectRelationship);

        }else if(null == de && disInfo.containsKey("distributorID")){
            //当前用户没有绑定推广员，并且链接含有推广员，则建立neo4j中用户与推广员有效期关系
            distributorID = disInfo.getInteger("distributorID");
            Distributor distributor2 = distributorService.selectById(distributorID);
            Position position = positionService.selectById(distributor2.getPositionID());
            distributorExpireRelationRepository.save(new DistributorExpireRelationship(sdf.format(new Date()),position.getDefaultValidationDays(),new N4jDistributor(distributor2.getUserID()),n4jUser));
            distributorProtectRelationRepository.save(new DistributorProtectRelationship(sdf.format(new Date()),position.getDefaultProtectionDays(),new N4jDistributor(distributor2.getUserID()),n4jUser));
        }else if(null!=de && de.getN4jDistributor().getDistributorID()==-1&& !disInfo.containsKey("distributorID")){
            //当前用户已经绑定虚拟推广员，且链接无推广员ID
            System.out.println("当前用户已经绑定虚拟推广员，并且链接中无推广员ID，不需修改有效期和保护期.");

        }else if(null!=de && de.getN4jDistributor().getDistributorID()==-1&& disInfo.containsKey("distributorID")){
            //当前用户已经绑定虚拟推广员,且链接有推广员ID,则更改绑定关系和有效期
            distributorID = disInfo.getInteger("distributorID");
            Distributor distPosition = distributorService.selectById(distributorID);
            Position position = positionService.selectById(distPosition.getPositionID());
            distributorExpireRelationRepository.updateRelationById(de.getId(),sdf.format(new Date()),position.getDefaultValidationDays(),new N4jDistributor(distributorID),n4jUser);
            distributorProtectRelationRepository.updateRelationById(de.getId(),sdf.format(new Date()),position.getDefaultProtectionDays(),new N4jDistributor(distributorID),n4jUser);

        }else if(null!=de && de.getN4jDistributor().getDistributorID()>0&& !disInfo.containsKey("distributorID")){
            //当前用户已经绑定其他非虚拟推广员,且链接没有推广员ID
            int days = 0;
            try {
                days = (int) ((new Date().getTime() - sdf.parse(de.getCreateTime()).getTime()) / (1000*3600*24));
                System.out.println("剩余有效期天数： "+days);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if(days>de.getExpireTime()){
                //超过绑定有效期，则更新绑定虚拟推广员
                distributorExpireRelationRepository.updateRelationById(de.getId(),sdf.format(new Date()),0,virtualN4jDistributor,n4jUser);
                distributorProtectRelationRepository.updateRelationById(de.getId(),sdf.format(new Date()),0,virtualN4jDistributor,n4jUser);

            }else {
                System.out.println("当前用户已经绑定其他非虚拟推广员,并且链接没有推广员ID，不需修改有效期和保护期.");
            }

        }else if(null!=de && de.getN4jDistributor().getDistributorID()>0&& disInfo.containsKey("distributorID")){
            //当前用户已经绑定其他非虚拟推广员,且链接有推广员ID,则根据两个推广员是否一样进行更改有效期，若一样，则恢复默认有效期和保护期,否则保持最先推广员不变
            distributorID = disInfo.getInteger("distributorID");
            int currProtectDays = 0;
            try {
                currProtectDays = (int) ((new Date().getTime() - sdf.parse(dp.getCreateTime()).getTime()) / (1000*3600*24));
                System.out.println("剩余有效期天数： "+currProtectDays);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            if(de.getN4jDistributor().getDistributorID() == distributorID){
                Distributor distPosition = distributorService.selectById(distributorID);
                Position position = positionService.selectById(distPosition.getPositionID());
                distributorExpireRelationRepository.updateRelationById(de.getId(),sdf.format(new Date()),position.getDefaultValidationDays(),new N4jDistributor(distributorID),n4jUser);
                distributorProtectRelationRepository.updateRelationById(de.getId(),sdf.format(new Date()),position.getDefaultProtectionDays(),new N4jDistributor(distributorID),n4jUser);
            }else if(de.getN4jDistributor().getDistributorID() != distributorID && currProtectDays<dp.getExpireTime()){
                System.out.println("当前推广用户点击了其他推广员的链接，而且当前用户没有过保护期，则不更新当前用户有效期和保护期.");

            }else if(de.getN4jDistributor().getDistributorID() != distributorID && currProtectDays>=dp.getExpireTime()){
                System.out.println("当前推广用户点击了其他推广员的链接，而且当前已经过了保护期，则更新推广用户的绑定有效期和保护期.");
                Distributor distPosition = distributorService.selectById(distributorID);
                Position position = positionService.selectById(distPosition.getPositionID());
                distributorExpireRelationRepository.updateRelationById(de.getId(),sdf.format(new Date()),position.getDefaultValidationDays(),new N4jDistributor(distributorID),n4jUser);
                distributorProtectRelationRepository.updateRelationById(de.getId(),sdf.format(new Date()),position.getDefaultProtectionDays(),new N4jDistributor(distributorID),n4jUser);

            }

        }

//        distributorID  = disInfo.getInteger("distributorID");
        //建立neo4j关联......用户与商品之间的点击关系,用户与推广员之间的点击关系
        ClickLinkRelationship clickLinkRelationship = new ClickLinkRelationship(sdf.format(new Date()),n4jUser,new N4jProduct(productID));
        this.clickLinkRelationRepository.save(clickLinkRelationship);


        ClickDistributorRelationship clickDistributorRelationship = new ClickDistributorRelationship(sdf.format(new Date()),new N4jDistributor(distributorID),n4jUser);
        this.clickDistributorRelationRepository.save(clickDistributorRelationship);


        Product product = productService.selectById(productID);
        Map condition = new HashMap();
        condition.put("productID",productID);
        List<Price> priceList = this.priceService.selectByMap(condition);
        JSONArray priceInfo = new JSONArray();
        for(Price price: priceList){
            JSONObject obj = new JSONObject();
            obj.put("specList",price.getSpecList());
            obj.put("leaderPrice",price.getLeaderPrice());
            obj.put("groupPrice",price.getGroupPrice());
            obj.put("instantPrice",price.getInstantPrice());
            priceInfo.add(obj);
        }
        JSONObject res = new JSONObject();
        res.put("name",product.getName());
        res.put("description",product.getDescription());
        res.put("smallPicture",product.getSmallPicture());
        res.put("priceInfo",priceInfo);
        return  new ResponseBean(200,"operation success",res);
    }

    /**
     * 商品信息及价格详情
     */
    @ApiOperation(value ="商品及价格详情")
    @ApiImplicitParam(name = "productId", value = "商品编号", required = true, dataType = "Integer")
    @RequestMapping(value = "/view/{productId}" ,method = RequestMethod.GET)
    @ResponseBody
    @RequiresAuthentication
    public Object view(@PathVariable("productId") Integer productId) {
        JSONObject json = (JSONObject) JSONObject.toJSON(productService.selectById(productId));
        Map<String,Object> condition  = new HashMap<>();
        condition.put("productID",productId);
        List<Price> priceList = this.priceService.selectByMap(condition);
        json.put("priceList",JSONArray.parseArray(JSON.toJSONString(priceList)));

//        json.remove("productID");
//        json.remove("isDeleted");
        return  new ResponseBean(200,"operation success",json);
    }


    /**
     * 查看商品海报图片
     */
    @ApiOperation(value ="查看商品海报图片")
    @ApiImplicitParam(name = "productID", value = "商品编号", required = true, dataType = "Integer")
    @RequestMapping(value = "/getPoster/{productID}" ,method = RequestMethod.GET)
    @ResponseBody
    @RequiresAuthentication
    public Object getPoster(@PathVariable("productID") Integer productID) {
        Product product = productService.selectById(productID);
        JSONObject json = new JSONObject();
        json.put("poster",product.getPoster());
        return  new ResponseBean(200,"operation success",json);
    }
    /**
     * 查看商品海报图片
     */
    @ApiOperation(value ="获取商品海报图片与二维码合成图")
    @ApiImplicitParam(name = "params", value = "json格式,包含productID、url等", required = true, dataType = "Map")
    @RequestMapping(value = "/getQrPoster",method = RequestMethod.POST)
    @ResponseBody
    @RequiresAuthentication
    public Object getQrPoster(@RequestBody JSONObject params) {
    	  String productID=params.get("productID").toString();
    	  String url=params.get("url").toString();
        Product product = productService.selectById(productID);
        JSONObject json = new JSONObject();
        String extensionChart="";
        json.put("poster",product.getPoster());
        byte[] qrCode=QrcodeUtils.createQrcode(url, 400, null);
        try {
        	extensionChart=NewImageUtils.getNewImage(product.getPoster(), qrCode);
        	json.put("extensionChart",extensionChart);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        return  new ResponseBean(200,"operation success",json);
    }
}
